using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAttack : MonoBehaviour
{
    public float startTime;
    public float time;
    public int damage;

    public float attackCd;
    public float startAttack;


    private Animator anim;
    private PolygonCollider2D coll2D ;   
    // Start is called before the first frame update
    void Start()
    {
        anim = GameObject.FindGameObjectWithTag("Player").GetComponent<Animator>();
        coll2D = GetComponent<PolygonCollider2D>();
    } 

    // Update is called once per frame 
    void Update()
    {
        Attack();
    }

    void Attack()
    {
        if (attackCd <= 0)
        {
            if (Input.GetButtonDown("Attack"))
            {
                anim.SetTrigger("Attack");
                SoundManager.Attack();
                attackCd = startAttack;
                StartCoroutine(StartAttack());
            }
        }
        else
        {
            attackCd -= Time.deltaTime;
        }
    }

    IEnumerator StartAttack()
    {
        yield return new WaitForSeconds(startTime);
        coll2D.enabled = true;
        StartCoroutine(disableHitbox());
    }
    IEnumerator disableHitbox()
    {
        yield return new WaitForSeconds(time);
        coll2D.enabled = false; 
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.CompareTag ("Enemy"))
        {
            other.GetComponent<Enemy>().TakeDamage(damage);
        }
    }
}
